
package cn.easyplatform.support.scripting;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.ImporterTopLevel;
import org.mozilla.javascript.Scriptable;

import java.util.HashMap;
import java.util.Map;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class RhinoScriptable extends ImporterTopLevel {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private Map<String, Object> map = new HashMap<String, Object>();

    public RhinoScriptable() {
    }

    public RhinoScriptable(Map<String, Object> map) {
        this.map.putAll(map);
    }

    public void putAll(Map<String, Object> map) {
        this.map.putAll(map);
    }

    @Override
    public Object get(String name, Scriptable start) {
        if (map.containsKey(name))
            return Context.javaToJS(map.get(name), this);
        return super.get(name, start);
    }

    @Override
    public void put(String name, Scriptable start, Object value) {
        map.put(name, value);
    }

    @Override
    public void delete(String name) {
        map.remove(name);
        super.delete(name);
    }

    public void clear() {
        for (String name : map.keySet())
            super.delete(name);
        map.clear();
    }

    public void setVariable(String name, Object value) {
        map.put(name, value);
    }

    public boolean containsKey(String key) {
        return map.containsKey(key);
    }

    public Map<String, Object> getScope() {
        return map;
    }

    public Object getVariable(String name) {
        return map.get(name);
    }
}
